package cloud.pangui.core.utils;

import cloud.pangui.core.exception.UtilsRuntimeException;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @Auther hepangui
 * @Date 2020/11/5 0005
 */
public class GzipUtils {
	/**
	 * 压缩
	 */
	public static byte[] zip(byte[] bs) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();    //不用关
		GZIPOutputStream outputStream = null;
		try {
			outputStream = new GZIPOutputStream(os);
			outputStream.write(bs);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					throw new UtilsRuntimeException(e);
				}
			}
		}
		return os.toByteArray();
	}

	/**
	 * 解压
	 */
	public static byte[] unzip(byte[] bs) {

		ByteArrayOutputStream os = new ByteArrayOutputStream();    //不用关
		ByteArrayInputStream is = null;                            //不用关
		GZIPInputStream gzipInputStream = null;

		try {
			is = new ByteArrayInputStream(bs);
			gzipInputStream = new GZIPInputStream(is);

			//
			byte[] buffer = new byte[1024];
			int c = -1;
			while ((c = gzipInputStream.read(buffer)) >= 0) {
				os.write(buffer, 0, c);
			}
			return os.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (gzipInputStream != null) {
				try {
					gzipInputStream.close();
				} catch (IOException e) {
					throw new UtilsRuntimeException(e);
				}
			}
		}
	}
}

